package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;

import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")

public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增套餐，向套餐表和套餐菜品关系表插入数据
     * @param setmealDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody  SetmealDto setmealDto){
        setmealService.saveWithDish(setmealDto);
        return R.success("新增成功");
    }

    /**
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> list(int page,int pageSize,String name){
        Page<Setmeal> pageInfo=new Page<>(page,pageSize);
        Page<SetmealDto> pageInfoDto=new Page<>(page,pageSize);
        LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper<>();
        //添加查询条件
        queryWrapper.like(name!=null,Setmeal::getName,name);
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        setmealService.page(pageInfo,queryWrapper);

        //拷贝
        BeanUtils.copyProperties(pageInfo,pageInfoDto,"records");

        List<Setmeal> records=pageInfo.getRecords();

        List<SetmealDto> list= records.stream().map((item)->{
            //拷贝普通属性
            SetmealDto setmealDto=new SetmealDto();
            BeanUtils.copyProperties(item,setmealDto);
            //查询分类名称，复制到setmealDto
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category!=null) {
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return  setmealDto;
        }).collect(Collectors.toList());

        pageInfoDto.setRecords(list);
        return R.success(pageInfoDto);
    }

    /**
     * 获取指定id的套餐信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> get(@PathVariable Long id){
        SetmealDto setmealDto = setmealService.getWithDish(id);
        return R.success(setmealDto);
    }
    /**
     * 修改套餐信息及setmeal_dish信息
     */
    @PutMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> update(@RequestBody SetmealDto setmealDto){
        setmealService.updateWithDish(setmealDto);
        return R.success("套餐修改成功");
    }
    /**
     * 删除该id的setmeal表和setmeal_dish表
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> delete(Long[] ids){

        for (Long id:ids
        ) {
            //查询该套餐是否可删除，必须处于停售状态
            LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(Setmeal::getId,id);
            queryWrapper.eq(Setmeal::getStatus,1);
            int count=setmealService.count(queryWrapper);
            if(count>0){
                //如果不能删除，抛出一个异常
                throw new CustomException("套餐正在售卖中，不能删除");
            }
            //删除数据
            setmealService.removeById(id);
            setmealDishService.removeById(id);
        }
        return R.success("套餐删除成功");
    }
    /**
     * 停售和起售某id的套餐
     */
    @PostMapping("/status/0")
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> Status(Long[] ids){
        for (Long id:ids
        ) {
            Setmeal setmeal = setmealService.getById(id);
            setmeal.setStatus(0);
            setmealService.updateById(setmeal);
        }
        return R.success("停售成功");
    }
    @PostMapping("/status/1")
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> Status1(Long[] ids){
        for (Long id:ids
        ) {
            Setmeal setmeal = setmealService.getById(id);
            //套餐起售菜品必须也要起售状态，查询菜品是否都起售
            LambdaQueryWrapper<SetmealDish> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(SetmealDish::getSetmealId,setmeal.getId());
            List<SetmealDish> list = setmealDishService.list(queryWrapper);
            for (SetmealDish setmealDish: list
                 ) {
                Long dishId = setmealDish.getDishId();
                Dish byId = dishService.getById(dishId);
                if(byId==null||byId.getStatus()==0){
                    throw new CustomException("菜品不存在或未起售!套餐起售失败!");
                }
            }

            //起售
            setmeal.setStatus(1);
            setmealService.updateById(setmeal);
        }
        return R.success("起售成功");
    }

    /**
     * 根据条件查询套餐数据
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    //Cacheable：先从redis缓存查询数据，根据key查到了直接返回，否则从数据库查，并添加到redis缓存.
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId+'_'+#setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal){
        //先从redis获取缓存数据，按照分类查询：川菜，儿童套餐等...
        //String key="setmeal_"+setmeal.getCategoryId()+"_"+setmeal.getStatus();
        //List<Setmeal> dishSetmealList = (List<Setmeal>) redisTemplate.opsForValue().get(key);
        //if(dishSetmealList!=null){
            //return R.success(dishSetmealList);
        //}

        Long categoryId = setmeal.getCategoryId();
        LambdaQueryWrapper<Setmeal> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(categoryId!=null,Setmeal::getCategoryId,categoryId);
        wrapper.eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus());
        wrapper.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> list = setmealService.list(wrapper);
        //数据库中该套餐分类下的数据放入redis
        //redisTemplate.opsForValue().set(key,list,30, TimeUnit.MINUTES);

        return R.success(list);
    }

}
